<template>
  <div>
    <div class="gva-search-box">
      <el-form ref="elSearchFormRef" :inline="true" :model="searchInfo" class="demo-form-inline" :rules="searchRule" @keyup.enter="onSubmit">
      <el-form-item label="创建日期" prop="createdAt">
      <template #label>
        <span>
          创建日期
          <el-tooltip content="搜索范围是开始日期（包含）至结束日期（不包含）">
            <el-icon><QuestionFilled /></el-icon>
          </el-tooltip>
        </span>
      </template>
      <el-date-picker v-model="searchInfo.startCreatedAt" type="datetime" placeholder="开始日期" :disabled-date="time=> searchInfo.endCreatedAt ? time.getTime() > searchInfo.endCreatedAt.getTime() : false"></el-date-picker>
       —
      <el-date-picker v-model="searchInfo.endCreatedAt" type="datetime" placeholder="结束日期" :disabled-date="time=> searchInfo.startCreatedAt ? time.getTime() < searchInfo.startCreatedAt.getTime() : false"></el-date-picker>
      </el-form-item>
        <el-form-item label="模板配置名称" prop="name">
         <el-input v-model="searchInfo.name" placeholder="搜索条件" />

        </el-form-item>
           <el-form-item label="平台类型：" prop="platId">
            <el-select v-model="searchInfo.platId" clearable placeholder="请选择" @clear="()=>{searchInfo.platId=undefined}">
              <el-option v-for="(item,key) in platOptions" :key="key" :label="item.label" :value="item.value" />
            </el-select>
            </el-form-item>
           <el-form-item label="是否有效:" prop="status">
            <el-select v-model="searchInfo.status" clearable placeholder="请选择" @clear="()=>{searchInfo.status=undefined}">
              <el-option v-for="(item,key) in productStatusOptions" :key="key" :label="item.label" :value="item.value" />
            </el-select>
            </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="onSubmit">查询</el-button>
          <el-button icon="refresh" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box">
        <div class="gva-btn-list">
            <el-button type="primary" icon="plus" @click="openDialog">新增</el-button>
            <el-popover v-model:visible="deleteVisible" :disabled="!multipleSelection.length" placement="top" width="160">
            <p>确定要删除吗？</p>
            <div style="text-align: right; margin-top: 8px;">
                <el-button type="primary" link @click="deleteVisible = false">取消</el-button>
                <el-button type="primary" @click="onDelete">确定</el-button>
            </div>
            <template #reference>
                <el-button icon="delete" style="margin-left: 10px;" :disabled="!multipleSelection.length" @click="deleteVisible = true">删除</el-button>
            </template>
            </el-popover>
        </div>
        <el-table
        ref="multipleTable"
        style="width: 100%"
        tooltip-effect="dark"
        :data="tableData"
        row-key="ID"
        @selection-change="handleSelectionChange"
        >
        <el-table-column type="selection" width="55" />
        <el-table-column align="left" label="ID" prop="ID" width="120" />
        <el-table-column align="left" label="模板名称" prop="name" width="160" />
        <el-table-column align="left" label="平台类型" prop="platId" width="120">
            <template #default="scope">
            {{ filterDict(scope.row.platId,platOptions) }}
            </template>
        </el-table-column>
        <!-- <el-table-column align="left" label="包名" prop="appId" width="160" /> -->
        <!-- <el-table-column align="left" label="渠道名" prop="channelId" width="120" /> -->
        <el-table-column align="left" label="未充值配置" prop="productIds" width="120" />
        <el-table-column align="left" label="已充值配置" prop="productIdsPaid" width="120" />
        <el-table-column align="left" label="是否有效" prop="status" width="120">
            <template #default="scope">
            {{ filterDict(scope.row.status,productStatusOptions) }}
            </template>
        </el-table-column>
        <el-table-column align="left" label="创建时间" width="180">
            <template #default="scope">{{ formatDate(scope.row.createTime) }}</template>
         </el-table-column>
         <el-table-column align="left" label="修改时间" width="180">
            <template #default="scope">{{ formatDate(scope.row.updateTime) }}</template>
         </el-table-column>
        <el-table-column align="left" label="操作" fixed="right">
            <template #default="scope">
            <!-- <el-button type="primary" link class="table-button" @click="getDetails(scope.row)">
                <el-icon style="margin-right: 5px"><InfoFilled /></el-icon>
                查看详情
            </el-button> -->
            <el-button type="primary" link icon="edit" class="table-button" @click="updateTProductTplUserFunc(scope.row)">变更</el-button>
            <el-button type="primary" link icon="delete" @click="deleteRow(scope.row)">删除</el-button>
            </template>
        </el-table-column>
        </el-table>
        <div class="gva-pagination">
            <el-pagination
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="page"
            :page-size="pageSize"
            :page-sizes="[10, 30, 50, 100]"
            :total="total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
            />
        </div>
    </div>
    <!-- 编辑弹框 -->
    <el-dialog v-model="updateShopShow" style="width: 1400px" lock-scroll :before-close="closeUpdateShopShow" title="选择商品" destroy-on-close>
     <div class="gva-search-box">
      <el-form :model="vpShopInfo" ref="elSearchFormRef" :inline="true" class="demo-form-inline" :rules="searchRule" @keyup.enter="onSubmit">
        <el-row :gutter ="5"> 
          <el-col :span ="8">
            <el-form-item label="产品名称" prop="productName">
               <el-input v-model="vpShopInfo.productName" placeholder="产品名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="3">
            <el-form-item>
            <el-button
              @click="getVpDataByProductNameV1"
            >
               查询
            </el-button>
          </el-form-item>
         </el-col>
         <el-col :span="2">
            <el-form-item>
            <el-button
              @click="restVpDataV1"
            >
               重置
            </el-button>
          </el-form-item>
         </el-col>
        </el-row>
        <el-table
          ref="form"
          v-loading="listLoading"
          :data="vpShopList"
          style="width: 100%"
          @selection-change="setSelectRows"
        >          
          <el-table-column
            label="ID"
            prop="ID"
            width="50"
          />
          <el-table-column
            label="商品名称"
            prop="productName"
            width="140"
          />
          <el-table-column
            label="原价"
            prop="originCost"
            width="70"
          />
          <el-table-column
            label="实际价格（分）"
            prop="cost"
            width="110"
          />
          <el-table-column
            label="看点（个）"
            prop="amount"
            width="100"
          />
          <el-table-column
            label="赠送看点（个）"
            prop="give"
            width="120"
          />
          <el-table-column
            label="角标样式"
            prop="logoStyle"
            width="80"
          />
          <el-table-column
            label="角标描述"
            prop="logoDesc"
            width="90"
          />
          <el-table-column
            label="档位描述"
            prop="description"
            width="95"
          />
          <el-table-column
            label="档位底色"
            prop="backgroundColor"
            width="90"
          />
          <el-table-column
            label="类型"
            prop="type"
            width="90"
          />
          <el-table-column
            label="状态"
            prop="status"
            width="90"
          />
          <el-table-column
            label="创建时间"
            prop="createTime"
            width="170"
          />

          <el-table-column
            label="操作"
            prop=""
            min-width="140px"
            fixed="right"
          >
          <template #default="scope">
              <el-button type="text" @click="chooseDataV1(scope.row)">选择</el-button>
          </template>
        </el-table-column>
        </el-table>
        <div class="gva-pagination">
            <el-pagination
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="page"
            :page-size="pageSize"
            :page-sizes="[10, 30, 50, 100]"
            :total="total"
            @current-change="handleCurrentChangeV1"
            @size-change="handleCurrentChangeV1"
            />
        </div>
       </el-form>
      </div>
    </el-dialog>

    <!-- 已充值档位配置选择弹框 -->
    <el-dialog v-model="topUpDialog" style="width: 1400px" lock-scroll :before-close="closeTopUpDialog" title="选择商品" destroy-on-close>
     <div class="gva-search-box">
      <el-form :model="vpShopInfo" ref="elSearchFormRef" :inline="true" class="demo-form-inline" :rules="searchRule" @keyup.enter="onSubmit">
        <el-row :gutter ="5"> 
          <el-col :span ="8">
            <el-form-item label="产品名称" prop="productName">
               <el-input v-model="vpShopInfo.productName" placeholder="产品名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="3">
            <el-form-item>
            <el-button
              @click="getVpDataByProductName"
            >
               查询
            </el-button>
          </el-form-item>
         </el-col>
         <el-col :span="2">
            <el-form-item>
            <el-button
              @click="restVpData"
            >
               重置
            </el-button>
          </el-form-item>
         </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-form-item>
            <el-button
              type="primary"
              @click="selectiveBackV1"
            >
            确定选择
            </el-button>
          </el-form-item>
        </el-row>
        <el-table
          ref="form"
          v-loading="listLoading"
          :data="vpShopList"
          style="width: 100%"
          @selection-change="setSelectRows"
        >
        <el-table-column type="selection"/> 

        <el-table-column
            label="ID"
            prop="ID"
            width="50"
          />
          <el-table-column
            label="商品名称"
            prop="productName"
            width="140"
          />
        <el-table-column  label="原价" prop="originCost" width="80">
            <template #default="scope">{{  scope.row.originCost>0 ?(scope.row.originCost/100).toFixed(2)+" 元": "0 元"}}</template>
         </el-table-column>
          <el-table-column
            label="实际价格（分）"
            prop="cost"
            width="110"
          />
          <el-table-column
            label="看点（个）"
            prop="amount"
            width="100"
          />
          <el-table-column
            label="赠送看点（个）"
            prop="give"
            width="120"
          />
          <el-table-column
            label="角标样式"
            prop="logoStyle"
            width="80"
          />
          <el-table-column
            label="角标描述"
            prop="logoDesc"
            width="90"
          />
          <el-table-column
            label="档位描述"
            prop="description"
            width="95"
          />
          <el-table-column
            label="档位底色"
            prop="backgroundColor"
            width="90"
          />
          <el-table-column
            label="类型"
            prop="type"
            width="90"
          />
          <el-table-column
            label="状态"
            prop="status"
            width="90"
          />
          <el-table-column
            label="创建时间"
            prop="createTime"
            width="170"
          />
          <!-- <el-table-column
            label="操作"
            prop=""
            min-width="140px"
            fixed="right"
          >
            <template #default="scope">
              <el-button type="text" @click="chooseData(scope.row)">选择</el-button>
            </template>
        </el-table-column> -->
        </el-table>
        <div class="gva-pagination">
            <el-pagination
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="page"
            :page-size="pageSize"
            :page-sizes="[10, 30, 50, 100]"
            :total="total"
            @current-change="handleCurrentChangeV1"
            @size-change="handleSizeChangeV1"
            />
        </div>
       </el-form>
      </div>
    </el-dialog>

    <!-- 未充值档位配置选择弹框 -->
    <el-dialog v-model="addShopShow" style="width: 1400px" lock-scroll :before-close="closeAddShopShow" title="选择商品" destroy-on-close>
     <div class="gva-search-box">
      <el-form :model="vpShopInfo" ref="elSearchFormRef" :inline="true" class="demo-form-inline" :rules="searchRule" @keyup.enter="onSubmit">
        <el-row :gutter ="5"> 
          <el-col :span ="8">
            <el-form-item label="产品名称" prop="productName">
               <el-input v-model="vpShopInfo.productName" placeholder="产品名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="3">
            <el-form-item>
            <el-button
              @click="getVpDataByProductName"
            >
               查询
            </el-button>
          </el-form-item>
         </el-col>
         <el-col :span="2">
            <el-form-item>
            <el-button
              @click="restVpData"
            >
               重置
            </el-button>
          </el-form-item>
         </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-form-item>
            <el-button
              @click="selectiveBack"
              type="primary"
            >
            确定选择
            </el-button>
          </el-form-item>
        </el-row>
        <el-table
          ref="form"
          v-loading="listLoading"
          :data="vpShopList"
          style="width: 100%"
          @selection-change="setSelectRows"
        >
        <el-table-column type="selection"/> 

        <el-table-column
            label="ID"
            prop="ID"
            width="50"
          />
          <el-table-column
            label="商品名称"
            prop="productName"
            width="140"
          />
          <el-table-column  label="原价" prop="originCost" width="80">
            <template #default="scope">{{  scope.row.originCost>0 ?(scope.row.originCost/100).toFixed(2)+" 元": "0 元"}}</template>
         </el-table-column>
          <el-table-column
            label="实际价格（分）"
            prop="cost"
            width="110"
          />
          <el-table-column
            label="看点（个）"
            prop="amount"
            width="100"
          />
          <el-table-column
            label="赠送看点（个）"
            prop="give"
            width="120"
          />
          <el-table-column
            label="角标样式"
            prop="logoStyle"
            width="80"
          />
          <el-table-column
            label="角标描述"
            prop="logoDesc"
            width="90"
          />
          <el-table-column
            label="档位描述"
            prop="description"
            width="95"
          />
          <el-table-column
            label="档位底色"
            prop="backgroundColor"
            width="90"
          />
          <el-table-column
            label="类型"
            prop="type"
            width="90"
          />
          <el-table-column
            label="状态"
            prop="status"
            width="90"
          />
          <el-table-column
            label="创建时间"
            prop="createTime"
            width="170"
          />
        </el-table>
        <div class="gva-pagination">
            <el-pagination
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="page"
            :page-size="pageSize"
            :page-sizes="[10, 30, 50, 100]"
            :total="total"
            @current-change="handleCurrentChangeV1"
            @size-change="handleSizeChangeV1"
            />
        </div>
       </el-form>
      </div>
    </el-dialog>

    <el-dialog v-model="dialogFormVisible" :before-close="closeDialog" :title="type==='create'?'添加':'修改'" destroy-on-close>
      <el-scrollbar height="580px">
          <el-form :model="formData" label-position="right" ref="elFormRef" :rules="rule" label-width="150px">
            
            <el-form-item label="模板名称"  prop="name" >
              <el-input v-model="formData.name" :clearable="true"  placeholder="请输入模板配置名称" />
            </el-form-item>
            
            <el-form-item label="平台类型"  prop="platId" >
              <el-select v-model="formData.platId" placeholder="请选择平台类型：" style="width:100%" :clearable="false" >
                <el-option v-for="(item,key) in platOptions" :key="key" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="包名"  prop="appId"  v-if="show">
              <el-select v-model="formData.appId" placeholder="请选择投放小程序" :clearable="true">
                  <el-option value="com.wyxh.wanyi"     label="com.wyxh.wanyi" />
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="渠道"  prop="channelId" >
              <el-input v-model="formData.channelId" :clearable="true"  placeholder="" />
            </el-form-item> -->
            <el-form-item label="未支付配置"  prop="productIds">
              <el-input v-model="formData.productIds" :clearable="true"  placeholder="请设置档位配置" :disabled = "true" />
            </el-form-item>
            <!-- <el-form-item label="档位配置排序:"  prop="productOrder" >
              <el-input v-model="formData.productOrder" :clearable="true"  placeholder="请输入档位配置排序" />
            </el-form-item> -->
            <el-form-item label="已支付配置"  prop="productIdsPaid">
              <el-input v-model="formData.productIdsPaid" :clearable="true"  placeholder="请设置已支付档位配置" :disabled = "true" />
            </el-form-item>
            <!-- <el-form-item label="已支付档位配置排序:"  prop="productOrderPaid" >
              <el-input v-model="formData.productOrderPaid" :clearable="true"  placeholder="请输入已支付档位配置排序" />
            </el-form-item> -->
            <el-form-item label="是否有效"  prop="status" >
              <el-radio-group v-model="formData.status">
                <el-radio :label="1">有效</el-radio>
                <el-radio :label="2">无效</el-radio>
              </el-radio-group>
            </el-form-item>
             <!-- 预留字段 -->
            <!-- <el-form-item label="充值模板名称:" prop="name">
               <el-input v-model="formData.name"/>
            </el-form-item> -->
           <el-tabs v-model="formData.activeName" @tab-click="handleTabClick">
            <el-tab-pane label="未充值档位" name="first"></el-tab-pane>
            <el-tab-pane label="已充值档位" name="second"></el-tab-pane>
           </el-tabs> 
           <el-form-item>
            <el-button
              v-if="addButtonV1"
              class="addGears"
              @click="addaddGearsData"
              type="primary"
            >
               未充值档位添加
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button
              v-if="addButton"
              class="addGearsv2"
              @click="addaddGearsDatav1"
              type="primary"
            >
               已充值档位添加
            </el-button>
          </el-form-item>     
          <div class="box">
        <div
          v-for="(item, index) in kpList"
          :key="item.id"
          class="item"
          :style="{ order: item.orderNum , 'background-color': item.backgroundColor === 1 ? 'white' : '#fade9e'}"
          :draggable="true"
           @dragstart="onDragStart(index)"
           @dragover.prevent="onDragOver"
           @start="dragBug"
           @drop="onDrop(index, $event)">
          <ul>
            <div class="frame">
              <!-- <li>{{ item.ID }}</li> -->
              <li class="logosc" :style ="{ 'background-color': item.logoStyle === '2' ? 'yellow' : (item.logoStyle === '3' ? 'red' : (item.logoStyle === '4' ? 'blue': '' ) )}">
                  {{ item.logoDesc }}
              </li>
                <div class="itemYd">
                  <li class="nameC">{{ item.productName }}</li>               
                  <li v-if="item.type == 1">
                     <li>{{item.amount}}点 + {{item.give}}点</li> 
                  </li>
                   <li v-else-if="item.type == 2">
                      <li>{{item.cost / 100}} 元</li> 
                   </li>     
                  <li>{{ item.description }}</li>
                </div>
            </div>
              <li> 
              <img class="deInc" src="@/assets/delcon.png" @click="delGearsData(index,item.ID)"/>
              <img class="upInc" src="@/assets/upcon.png" @click="upGearsPage(item)" />
            </li>
          </ul> 
        </div>
      </div>
            <!-- <el-form-item label="排序号:"  prop="orderNum" >
              <el-input v-model.number="formData.orderNum" :clearable="true" placeholder="请输入排序号" />
            </el-form-item>
            <el-form-item label="创建人:"  prop="createUid" >
              <el-input v-model.number="formData.createUid" :clearable="true" placeholder="请输入创建人" />
            </el-form-item>
            <el-form-item label="更新人:"  prop="updateUid" >
              <el-input v-model.number="formData.updateUid" :clearable="true" placeholder="请输入更新人" />
            </el-form-item> -->
          </el-form>
      </el-scrollbar>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="enterDialog">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="detailShow" style="width: 800px" lock-scroll :before-close="closeDetailShow" title="查看详情" destroy-on-close>
      <el-scrollbar height="550px">
        <el-descriptions column="1">
                <el-descriptions-item label="模板配置名称">
                        {{ formData.name }}
                </el-descriptions-item>
                <el-descriptions-item label="平台类型：">
                        {{ filterDict(formData.platId,platOptions) }}
                </el-descriptions-item>
                <el-descriptions-item label="包名">
                        {{ formData.appId }}
                </el-descriptions-item>
                <el-descriptions-item label="渠道， 每个渠道一条记录">
                        {{ formData.channelId }}
                </el-descriptions-item>
                <el-descriptions-item label="档位配置">
                        {{ formData.productIds }}
                </el-descriptions-item>
                <!-- <el-descriptions-item label="档位配置排序">
                        {{ formData.productOrder }}
                </el-descriptions-item> -->
                <el-descriptions-item label="已支付档位配置">
                        {{ formData.productIdsPaid }}
                </el-descriptions-item>
                <!-- <el-descriptions-item label="已支付档位配置排序">
                        {{ formData.productOrderPaid }}
                </el-descriptions-item> -->
                <el-descriptions-item label="是否有效:">
                        {{ filterDict(formData.status,productStatusOptions) }}
                </el-descriptions-item>
                <!-- <el-descriptions-item label="排序号">
                        {{ formData.orderNum }}
                </el-descriptions-item>
                <el-descriptions-item label="创建人">
                        {{ formData.createUid }}
                </el-descriptions-item>
                <el-descriptions-item label="更新人">
                        {{ formData.updateUid }}
                </el-descriptions-item> -->
        </el-descriptions>
      </el-scrollbar>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  createTProductTplUser,
  deleteTProductTplUser,
  deleteTProductTplUserByIds,
  updateTProductTplUser,
  findTProductTplUser,
  getTProductTplUserList
} from '@/api/tProductTplUser'

// 全量引入格式化工具 请按需保留
import { getDictFunc, formatDate, formatBoolean, filterDict, ReturnArrImg, onDownloadFile } from '@/utils/format'
import { ElMessage, ElMessageBox } from 'element-plus'


import {
  getTProductList,
  getTProductListByIds,
  updateTProduct,
  getTProductListByProductName
} from '@/api/tProduct'


// import { ref, reactive } from 'vue'

// vue3 组件拖动  引入插件
// import draggable from 'vuedraggable';

// import { VueDraggableNext } from 'vue-draggable-next'

import { reactive, toRefs, onMounted, ref } from 'vue'

let draggedIndex = null;

const onDragStart = (index) => {
  draggedIndex = index;
};

const onDragOver = (event) => {
  event.preventDefault();
};

 const dragBug = (evt) => {
    // this.$nextTick(() => {
    var e = evt || window.event;
    var chosen = document.querySelector('.sortable-fallback');1
    chosen.style.top = e.item.offsetTop + 'px';
    // });
}


const onDrop = (targetIndex, event) => {
  event.preventDefault();
  if (draggedIndex !== targetIndex) {
    const targetOrder = kpList.value[targetIndex].orderNum;
    const draggedOrder = kpList.value[draggedIndex].orderNum;
    kpList.value[targetIndex].orderNum = draggedOrder; 
    kpList.value[draggedIndex].orderNum = targetOrder;
    const idList = JSON.parse(JSON.stringify(kpList.value))
    var dataList = []
    for (var i in idList) {
      dataList.push(idList[i])
    }
    
    dataList = dataList.sort(sortBy('orderNum'))

    var idsString = []
    for (var i = 0; i < dataList.length; i++) {
      if (idsString.length > 0) {
        idsString += ','
      }
      idsString += dataList[i].ID
    }

    // 判断是未充值还是已充值
    if (formData.value.wczType == 1) {
       // 未充值档位
       formData.value.productIds = idsString    
    } else if(formData.value.wczType == 2){
         // 已充值档位
      formData.value.productIdsPaid = idsString     
    }
  }
}

const sortBy = (attr, rev) => {
  //第二个参数没有传递 默认升序排列
  if(rev == undefined) {
    rev = 1
  } else {
    rev = (rev) ? 1 : -1
  }

  return function(a, b) {
    a = a[attr]
    b = b[attr]
  if(a < b) {
    return rev * -1
      }
    if(a > b) {
      return rev * 1
  }
  return 0
  }
}


defineOptions({
    name: 'TProductTplUser'
})

const kpList = ref([])
const selectRows = ref([])
// vip添加商品table数据
const vpShopList=ref([])
// vp添加商品框
const vpShopInfo = ref({
    prProductId:'',
    productName: '',
   // 未付费充值档位信息
   productIds: [],
   // 已付费充值档位信息
   productIdsPaid: [],
   productIds:'',
   productIdsPaid:'',
   activeName:'first'
})

const setSelectRows= (val) => {
   selectRows.value = val
  }   

// vip充值 商品点击方法
const vpAddClick = () => {
  // 打开弹窗
  openAddShopShow()  
  // 查询档位数据,渲染table页
  handelInputV5()
}


// 编辑弹框
const upGearsPage =(item) =>{
  vpShopInfo.value.productName = ''
  // 获取当前选中的id
  vpShopInfo.value.prProductId = item.ID
  updateShopShow.value = true
  addPtGearsData()
}

// 普通充值页配置/添加商品文件
const addPtGearsData = async() => {
    const table= await getTProductList({page: page.value, pageSize: pageSize.value, ...vpShopInfo.value})
    for(var i=0; i< table.data.list.length; i++){
      if(table.data.list[i].logoStyle2 == 2){
        table.data.list[i].logoStyle = "黄"
      } else if(table.data.list[i].logoStyle2 == 3){
        table.data.list[i].logoStyle = "红"
      }else if(table.data.list[i].logoStyle2 == 4){
        table.data.list[i].logoStyle = "蓝"
      }
      if (table.data.list[i].type == 1) {
        table.data.list[i].type = "看点"
      }else if(table.data.list[i].type == 2){
        table.data.list[i].type = "VIP"
      }else if(table.data.list[i].type == 3){
        table.data.list[i].type = "解锁全集"
      }
      if (table.data.list[i].backgroundColor == 1) {
        table.data.list[i].backgroundColor = "无"
      }else if(table.data.list[i].backgroundColor == 2){
        table.data.list[i].backgroundColor = "黄"
      }
      if (table.data.list[i].status == 1) {
        table.data.list[i].status = "有效"
      }else if(table.data.list[i].status == 2){
        table.data.list[i].status = "无效"
      }
    }
    vpShopList.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
}

// 点击重置,重置文本框内容
const restVpData = async() => {
  // 清空文本框
  vpShopInfo.value.productName = ''
  // 渲染页面调用查询方法
  handelInputV5()
}


// vp查询,根据产品名称查询
const getVpDataByProductName = async() => {
  handelInputV6()
}

// 根据产品名称查询档位数据
const handelInputV6  = async() => {
  const {data} = await getTProductListByProductName(vpShopInfo.value.productName)
  vpShopList.value =data.list
  total.value = data.total

}

// 查询档位数据,渲染table页
const handelInputV5  = async() => {
    const table= await getTProductList({page: page.value, pageSize: pageSize.value, ...vpShopInfo.value})
     // 角标样式
    for(var i=0; i< table.data.list.length; i++){
      if(table.data.list[i].logoStyle2 == 2){
        table.data.list[i].logoStyle = "黄"
      } else if(table.data.list[i].logoStyle2 == 3){
        table.data.list[i].logoStyle = "红"
      }else if(table.data.list[i].logoStyle2 == 4){
        table.data.list[i].logoStyle = "蓝"
      }
      if (table.data.list[i].type == 1) {
        table.data.list[i].type = "看点"
      }else if(table.data.list[i].type == 2){
        table.data.list[i].type = "VIP"
      }else if(table.data.list[i].type == 3){
        table.data.list[i].type = "解锁全集"
      }
      if (table.data.list[i].backgroundColor == 1) {
        table.data.list[i].backgroundColor = "无"
      }else if(table.data.list[i].backgroundColor == 2){
        table.data.list[i].backgroundColor = "黄"
      }
      if (table.data.list[i].status == 1) {
        table.data.list[i].status = "有效"
      }else if(table.data.list[i].status == 2){
        table.data.list[i].status = "无效"
      }
    }
    vpShopList.value = table.data.list

    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
}
 

// 删除档位信息
const delGearsData = async(index,ID) => {
  kpList.value.splice(index, 1)
  if(formData.value.wczType == 1){
    // 未充值
    const idArrList =formData.value.productIds.split(',')
    formData.value.productIds  = '' 
    for(var i =0; i< idArrList.length; i++){
     if(idArrList[i] != ID){
      if (formData.value.productIds.length > 0) {
        formData.value.productIds +=","
      }   
       formData.value.productIds += idArrList[i]
    }
  }
}else if(formData.value.wczType == 2){
   // 已充值
   const idArrList =formData.value.productIdsPaid.split(',')
    formData.value.productIdsPaid  = '' 
    for(var i =0; i< idArrList.length; i++){
     if(idArrList[i] != ID){
      if (formData.value.productIdsPaid.length > 0) {
        formData.value.productIdsPaid +=","
      }
       formData.value.productIdsPaid += idArrList[i]
    }
  }
} 
}


// vip 添加商品弹窗
const openAddShopShow = ()=>{
  addShopShow.value = true
}

// 关闭vip 添加商品控制弹框
const closeAddShopShow = ()=>{
  addShopShow.value = false
}

const closeTopUpDialog =() =>{
  topUpDialog.value = false
}

// 重置按钮
const restVpDataV1 = async() => {
    // 清空文本框
    vpShopInfo.value.productName = ''
    addPtGearsData()
}

// 编辑 根据名称查询
const getVpDataByProductNameV1 = async() => {
  handelInputV7()
}

// 编辑查询
const handelInputV7  = async() => {
  const {data} = await getTProductListByProductName(vpShopInfo.value.productName)
  vpShopList.value =data.list
  total.value = data.total
}


// 未充值档位
const addaddGearsData = async() =>{
    // 清空查询条件
    vpShopInfo.value.productName = ''
    page.value = ''
    openAddShopShow()  
    if(formData.value.productIds !=='undefined' && formData.value.productIds !=null && formData.value.productIds !==""){
         formData.value.productIdList = formData.value.productIds+','
    } else {
    formData.value.productIdList = formData.value.productIds
  }
    // 查询档位数据,渲染table页
  handelInputV5()
} 

 // 已充值档位
const addaddGearsDatav1 = async() =>{
     vpShopInfo.value.productName = ''
    page.value = ''
    // 打开弹窗
    topUpDialog.value  = true
    if(formData.value.productIdsPaid !=='undefined' && formData.value.productIdsPaid !=null && formData.value.productIdsPaid !==""){
    formData.value.productIdsPaidList = formData.value.productIdsPaid+','
  } else {
    formData.value.productIdsPaidList = formData.value.productIdsPaid
  }
    // 查询档位数据,渲染table页
    handelInputV5()
} 

//选项卡带回档位数据
const handleTabClick = async(tab, event) => {
  // 点击未充值档位，隐藏已充值档位按钮
  if (tab.index == 0) {
    addButton.value = false
    addButtonV1.value = true
    formData.value.wczType = 1  
    // 未充值档位数据
  if (formData.value.productIds != null) {
      // 未付费用户
      const idList = formData.value.productIds
      const idArray = idList.split(',')
      const ids = []
      for(var i = 0; i<idArray.length; i++){
        ids.push(parseInt(idArray[i]))
      }
      let dataList = []
      let {data}  = await getTProductListByIds({ ids })
      for(let i= 0; i < ids.length; i++){
          for(var j= 0; j< data.list.length; j++){
            if(ids[i] == data.list[j].ID) {
              data.list[j].orderNum= i
              dataList.push(data.list[j])
              }    
           }
        }
      kpList.value = dataList
    } 
  } else if (tab.index == 1) {
    formData.value.wczType = 2
    
    // 点击已充值档位，隐藏未充值档位按钮
    addButtonV1.value = false
   
    addButton.value =true

    // 已充值档位 
    // 根据档位ids值回显数据
    if (formData.value.productIdsPaid != null) {
    const idList = formData.value.productIdsPaid
    const idArray = idList.split(',')
    const ids = []
    for(var i = 0; i<idArray.length; i++){
      ids.push(parseInt(idArray[i]))
    }
    let dataList = []
    let {data}  = await getTProductListByIds({ ids })
    for(let i= 0; i < ids.length; i++){
          for(var j= 0; j< data.list.length; j++){
            if(ids[i] == data.list[j].ID) {
              data.list[j].orderNum= i
              dataList.push(data.list[j])
              }    
           }
        }
      kpList.value = data.list
    }
  }
}


// 未充值档位带回数据
const selectiveBack  = async() => { 
  const rows = selectRows.value
   if (rows == null || rows.length === 0) {
     ElMessage({
          type: 'warning',
          message: '未选中任何数据........'
        })
     return
   } 
    const selectIds = []
     for (let i = 0; i < rows.length; i++) {
        selectIds.push(rows[i].ID)
      }
      const setIds = new Set(selectIds)
      const setIdList =Array.from(setIds).toString()
      if (formData.value.productIdList !=null) {
          //回显文本框内容
          vpShopInfo.value.productIds = formData.value.productIdList + setIdList 
          let arrList = vpShopInfo.value.productIds.split(',')
          let set = new Set(arrList)
          arrList = Array.from(set)
          // 未付费充值档位
          formData.value.productIds = Array.from(arrList).toString()
      }else {
        formData.value.productIds = setIdList
      }
      // 关闭点击弹窗
      closeAddShopShow()
      if (formData.value.productIds != null) {
      // 未付费用户
      const idList = formData.value.productIds
      const idArray = idList.split(',')
      const ids = []
      for(var i = 0; i<idArray.length; i++){
        ids.push(parseInt(idArray[i]))
      }
      let {data}  = await getTProductListByIds({ ids })
      let dataList = []
      for(let i= 0; i < ids.length; i++){
          for(var j= 0; j< data.list.length; j++){
            if(ids[i] == data.list[j].ID) {
              data.list[j].orderNum= i
              dataList.push(data.list[j])
              }    
           }
        }
      kpList.value = dataList
    } 
}

// 已充值档位带回数据
const selectiveBackV1  = async() => {
   const rows = selectRows.value
   if (rows == null || rows.length === 0) {
    ElMessage({
          type: 'warning',
          message: '未选中任何数据........'
        })
     return
   } 
    const selectIds = []
     for (let i = 0; i < rows.length; i++) {
        selectIds.push(rows[i].ID)
      }
      const setIds = new Set(selectIds)
      const setIdList =Array.from(setIds).toString()

      if (formData.value.productIdsPaidList !=null) {
           // 回显文本框内容
          vpShopInfo.value.productIdsPaid = formData.value.productIdsPaidList + setIdList 
          let arrList = vpShopInfo.value.productIdsPaid.split(',')
          let set = new Set(arrList)
          arrList = Array.from(set)
          // 已付费充值档位
          formData.value.productIdsPaid = Array.from(arrList).toString()
      }else{
        formData.value.productIdsPaid = setIdList
    }  
      // 关闭点击弹窗
      closeTopUpDialog()

    if (formData.value.productIdsPaid != null) {
        const idList = formData.value.productIdsPaid
        const idArray = idList.split(',')
        const ids = []
        for(var i = 0; i<idArray.length; i++){
          ids.push(parseInt(idArray[i]))
        }
        let {data}  = await getTProductListByIds({ ids })
        let dataList = []
        for(let i= 0; i < ids.length; i++){
          for(var j= 0; j< data.list.length; j++){
            if(ids[i] == data.list[j].ID) {
              data.list[j].orderNum= i
              dataList.push(data.list[j])
              }    
           }
        }
        kpList.value = dataList
       }
    }




// 自动化生成的字典（可能为空）以及字段
const platOptions = ref([])
const productStatusOptions = ref([])
const formData = ref({
        name: '',
        platId: '',
        appId: 'com.wyxh.wanyi',
        channelId: '',
        productIds: '',
        productOrder: '',
        productIdsPaid: '',
        productOrderPaid: '',
        status: 1,
        orderNum: 0,
        createUid: 0,
        updateUid: 0,
        productIdList:'',
        productIdsPaidList:'',
        activeName:'first'
    })


// 验证规则
const rule = reactive({
               name : [{
                   required: true,
                   message: '',
                   trigger: ['input','blur'],
               },
               {
                   whitespace: true,
                   message: '不能只输入空格',
                   trigger: ['input', 'blur'],
              }
              ],
               platId : [{
                   required: true,
                   message: '',
                   trigger: ['input','blur'],
               },
              ],
               appId : [{
                   required: true,
                   message: '',
                   trigger: ['input','blur'],
               },
               {
                   whitespace: true,
                   message: '不能只输入空格',
                   trigger: ['input', 'blur'],
              }
              ],
               productIds : [{
                   required: true,
                   message: '未支付档位配置不能为空',
                  // trigger: ['input','blur'],
               },
               {
                   whitespace: true,
                   message: '不能只输入空格',
                   trigger: ['input', 'blur'],
              }
              ],
               productIdsPaid : [{
                   required: true,
                   message: '已支付档位配置不能为空',
                   // trigger: ['input','blur'],
               },
               {
                   whitespace: true,
                   message: '不能只输入空格',
                   trigger: ['input', 'blur'],
              }
              ],
               status : [{
                   required: true,
                   message: '',
                   trigger: ['input','blur'],
               },
              ],
})

const searchRule = reactive({
  createdAt: [
    { validator: (rule, value, callback) => {
      if (searchInfo.value.startCreatedAt && !searchInfo.value.endCreatedAt) {
        callback(new Error('请填写结束日期'))
      } else if (!searchInfo.value.startCreatedAt && searchInfo.value.endCreatedAt) {
        callback(new Error('请填写开始日期'))
      } else if (searchInfo.value.startCreatedAt && searchInfo.value.endCreatedAt && (searchInfo.value.startCreatedAt.getTime() === searchInfo.value.endCreatedAt.getTime() || searchInfo.value.startCreatedAt.getTime() > searchInfo.value.endCreatedAt.getTime())) {
        callback(new Error('开始日期应当早于结束日期'))
      } else {
        callback()
      }
    }, trigger: 'change' }
  ],
})

const elFormRef = ref()
const elSearchFormRef = ref()

// =========== 表格控制部分 ===========
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const searchInfo = ref({})

const addButton = ref(true)
const addButtonV1 = ref(true)

// 重置
const onReset = () => {
  searchInfo.value = {}
  getTableData()
}

// 搜索
const onSubmit = () => {
  elSearchFormRef.value?.validate(async(valid) => {
    if (!valid) return
    page.value = 1
    pageSize.value = 10
    getTableData()
  })
}


// 添加带回 列表分页
 const handleSizeChangeV1 =(val) => {
    pageSize.value = val
    handelInputV5()
 }
  
 const handleCurrentChangeV1 = (val) =>{
    page.value = val
    handelInputV5()
 }


// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

// 修改页面容量
const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

//选择档位，修改当前选中的档为信息
const chooseDataV1 = async(row) => {
  let gearId = row.ID;
  for(var j in kpList.value){
     // 判断如果集合中的id == 当前选中的rowID 
     if(kpList.value[j].ID == gearId){ 
      ElMessage({
          type: 'warning',
          message: '选中的档位已存在,请重新选择'
        })
        return
    }
  }
  const idList = JSON.parse(JSON.stringify(kpList.value))
  var dataList = []
  let idArrList = []
  // 循环列表值
  for (var i in idList) {
    if(idList[i].ID == vpShopInfo.value.prProductId){
      row.orderNum = idList[i].orderNum
      idList[i] = row
      i = row.ID  
      dataList.push(JSON.parse(JSON.stringify(row)))
    } else{
      dataList.push(idList[i])
    }
  }
  dataList = dataList.sort(sortBy('orderNum'))
 
  for(var i = 0; i < dataList.length; i++){
    idArrList.push(dataList[i].ID)
  }
  // 判断选项卡是未充值还是已充值
  if (formData.value.wczType == 1) {
    // 未充值带回
     formData.value.productIds = ''
     formData.value.productIds = idArrList.toString()
    } else if(formData.value.wczType == 2){
      // 已充值带回
    formData.value.productIdsPaid = ''
    formData.value.productIdsPaid = idArrList.toString()
  }   
  kpList.value = idList
  closeUpdateShopShow()
}


// 选择档位信息 
const chooseData = async(row) => {     
    kpList.value.push(row)
   //根据当前选中的产品名称去查询档位数据
   handelInputV6()
   // 关闭添加弹框
   closeAddShopShow()
}

// 查询
const getTableData = async() => {
  const table = await getTProductTplUserList({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}
getTableData()

// ============== 表格控制部分结束 ===============

// 获取需要的字典 可能为空 按需保留
const setOptions = async () =>{
    platOptions.value = await getDictFunc('plat')
    productStatusOptions.value = await getDictFunc('productStatus')
}

// 获取需要的字典 可能为空 按需保留
setOptions()


// 多选数据
const multipleSelection = ref([])
// 多选
const handleSelectionChange = (val) => {
    multipleSelection.value = val
}

// 删除行
const deleteRow = (row) => {
    ElMessageBox.confirm('确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
            deleteTProductTplUserFunc(row)
        })
    }


// 批量删除控制标记
const deleteVisible = ref(false)


// 编辑控制按钮
const updateShopShow = ref(false)
  

const closeUpdateShopShow = ()=>{
  updateShopShow.value = false
}


// 多选删除
const onDelete = async() => {
      const ids = []
      if (multipleSelection.value.length === 0) {
        ElMessage({
          type: 'warning',
          message: '请选择要删除的数据'
        })
        return
      }
      multipleSelection.value &&
        multipleSelection.value.map(item => {
          ids.push(item.ID)
        })
      const res = await deleteTProductTplUserByIds({ ids })
      if (res.code === 0) {
        ElMessage({
          type: 'success',
          message: '删除成功'
        })
        if (tableData.value.length === ids.length && page.value > 1) {
          page.value--
        }
        deleteVisible.value = false
        getTableData()
      }
    }

// 行为控制标记（弹窗内部需要增还是改）
const type = ref('')

// 更新行
const updateTProductTplUserFunc = async(row) => {
  // 对于两个不同的button做隐藏操作
  addButton.value = false 
  addButtonV1.value = true
  const res = await findTProductTplUser({ ID: row.ID })
  type.value = 'update'
  if (res.code === 0) {
    formData.value = res.data.retProductTplUser
    formData.value.activeName = 'first'
    formData.value.wczType = 1
    formData.value.status = 1
    dialogFormVisible.value = true
  }
   // 未付费充值
   if (res.data.retProductTplUser.productIds != null) {
         // 未付费用户
         const idList = res.data.retProductTplUser.productIds
         const idArray = idList.split(',')
         const ids = []
         for(var i = 0; i<idArray.length; i++){
          ids.push(parseInt(idArray[i]))
        }
        let dataList = []
        let { data }  = await getTProductListByIds({ ids })
        for(let i= 0; i < ids.length; i++){
          for(var j= 0; j< data.list.length; j++){
            if(ids[i] == data.list[j].ID) {
              data.list[j].orderNum= i
              dataList.push(data.list[j])
              }    
           }
        }
      kpList.value = dataList
    } 
}

// 删除行
const deleteTProductTplUserFunc = async (row) => {
    const res = await deleteTProductTplUser({ ID: row.ID })
    if (res.code === 0) {
        ElMessage({
                type: 'success',
                message: '删除成功'
            })
            if (tableData.value.length === 1 && page.value > 1) {
            page.value--
        }
        getTableData()
    }
}

// 弹窗控制标记
const dialogFormVisible = ref(false)


// 查看详情控制标记
const detailShow = ref(false)

// VP添加商品控制编辑
const addShopShow = ref(false)

const topUpDialog = ref(false)

// 打开详情弹窗
const openDetailShow = () => {
  detailShow.value = true
}


// 打开详情
const getDetails = async (row) => {
  // 打开弹窗
  const res = await findTProductTplUser({ ID: row.ID })
  if (res.code === 0) {
    formData.value = res.data.retProductTplUser
    openDetailShow()
  }
}


// 关闭详情弹窗
const closeDetailShow = () => {
  detailShow.value = false
  formData.value = {
          name: '',
          platId: '',
          appId: '',
          channelId: '',
          productIds: '',
          productOrder: '',
          productIdsPaid: '',
          productOrderPaid: '',
          status: undefined,
          orderNum: 0,
          createUid: 0,
          updateUid: 0,
          wczType: 1,
          activeName:'first'
      }
}


// 打开弹窗
const openDialog = () => {
    type.value = 'create'
    dialogFormVisible.value = true 
    // 点击新增 清空列表缓存值
    kpList.value  = []
    // 对于两个不同的button做隐藏操作
   addButton.value = false 
   addButtonV1.value = true
   formData.value.wczType = 1
}

// 未充值挡位数据/已充值档位数据
const gearsData = async() => {   
  const data = await getTProductList().then(response =>{
    kpList.value = response.data.list
  })
}

// 关闭弹窗
const closeDialog = () => {
    dialogFormVisible.value = false
    formData.value = {
        name: '',
        platId: '',
        appId: 'com.wyxh.wanyi',
        channelId: '',
        productIds: '',
        productOrder: '',
        productIdsPaid: '',
        productOrderPaid: '',
        status: 1,
        orderNum: 0,
        createUid: 0,
        updateUid: 0,
        activeName:'first'
     }
}
// 弹窗确定
const enterDialog = async () => {
     elFormRef.value?.validate( async (valid) => {
             if (!valid) return
              let res
              switch (type.value) {
                case 'create':
                  res = await createTProductTplUser(formData.value)
                  break
                case 'update':
                  res = await updateTProductTplUser(formData.value)
                  break
                default:
                  res = await createTProductTplUser(formData.value)
                  break
              }
              if (res.code === 0) {
                ElMessage({
                  type: 'success',
                  message: '创建/更改成功'
                })
                closeDialog()
                getTableData()
              }
      })
}

</script>

<style scoped>

.deInc {
  position:relative;
  left:155px;
  bottom:33px;
}

.upInc{
  position:relative;
  left:159px;
  bottom:33px;
}

.nameC{
  font-size:17px;
}

.itemYd{
   position:relative;
   bottom:10px;
}

.pict{
  position:relative;
  bottom:35px;
  left:155px;
}

.frame{
  width: 165px;
  height: 55px;
  border: 1px solid #ebebeb;
  padding: 30px 0px 30px 30px;
  margin: 40px auto;
  margin-top:160px;
}

.addGearsv2{
  position:absolute;
  left:380px;
}

.addGears{
  position:absolute;
  left:380px;
  top: 2px;
}


.box {
  display: flex;
  flex-wrap: wrap; 
  width: 650px;
  margin-top: -36px;
}

ul li{
  /* margin-bottom: 10px */
   line-height: 30px
}

ul {
  margin-bottom:105px;
}

.logosc{
  width: fit-content;
  height:25px;
  color: white; 
  border-radius: 15px 0px 0px 15px;
  float: right;
  position: relative;
  bottom: 28px;
} 

.item {
  width: 235px;
  height: 170px;
  border: 1px solid #ccc;
  background-color: #f3f3f3;
  margin: 5px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 16px;
  cursor: move;
  user-select: none;
  transition: background-color 0.3s;
  margin-bottom:15px;
}
</style>
